package edu.nf.utils;



import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.Map;

/**
 * 将结果集转换成Bean对象
 */
public class BeanUtil {

    private static Map<Class, Object> primitiveDefaults = new HashMap<Class, Object>();

    static {
        primitiveDefaults.put(Integer.TYPE, Integer.valueOf(0));
        primitiveDefaults.put(Short.TYPE, Short.valueOf((short) 0));
        primitiveDefaults.put(Byte.TYPE, Byte.valueOf((byte) 0));
        primitiveDefaults.put(Float.TYPE, Float.valueOf(0f));
        primitiveDefaults.put(Double.TYPE, Double.valueOf(0d));
        primitiveDefaults.put(Long.TYPE, Long.valueOf(0L));
        primitiveDefaults.put(Boolean.TYPE, Boolean.FALSE);
        primitiveDefaults.put(Character.TYPE, Character.valueOf((char) 0));
    }

    /**
     * 根据Class对象创建bean对象，并将结果集中的数据赋值给bean
     *
     * @param rs
     * @param clazz
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T createBean(ResultSet rs, Class<T> clazz) {
        T t = null;
        try {
			//创建一个实体
            t = clazz.newInstance();
			//为实体赋值
            ResultSetMetaData md = rs.getMetaData();//获取结果集的列数
            for (int i = 1; i <= md.getColumnCount(); i++) {
                String columnName = md.getColumnLabel(i);//获取每一列的列名
                setField(t, columnName, clazz, rs);//根据列名找到对应的属性，并赋值
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return t;
    }

    /**
     * 为bean对象赋值
     *
     * @param bean       bean对象
     * @param columnName 数据库中的列名
     * @param clazz      bean对象对应的class对象
     * @param rs         结果集对象
     */
    public static void setField(Object bean, String columnName,
                                Class clazz, ResultSet rs) throws Exception {
        Field[] fields = clazz.getDeclaredFields();

        for (Field f : fields) {
            f.setAccessible(true);
            String tagName = f.isAnnotationPresent(Column.class) ?
                    f.getAnnotation(Column.class).value() : f.getName();

            if (tagName.equalsIgnoreCase(columnName)) {
                Object value = ColumnUtil.columnConvert(columnName, rs, f.getType());
                //空值处理
                if (value == null && f.getType().isPrimitive()) {
                    value = primitiveDefaults.get(f.getType());
                }
                f.set(bean, value);
                break;
            }

        }

    }

}
